package com.zhuoshi.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.zhuoshi.bean.WdHtRoom;
import com.zhuoshi.mapper.WdHtRoomMapper;
import com.zhuoshi.serviceImpl.RedisOpera;

import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisListener implements  ServletContextListener{

	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("清楚redis==============================");
		
	    JedisPool jedisPool = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getBean(JedisPool.class);
        WdHtRoomMapper roomMapper = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getBean(WdHtRoomMapper.class);
        System.out.println("朋友再见！！===========================");
        
      //获取ShardedJedis对象
        Jedis jedis = jedisPool.getResource();
        
        jedis.flushAll();
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0)
	{
		System.out.println("========================================插入redis数据！");
	    JedisPool jedisPool = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getBean(JedisPool.class);
        WdHtRoomMapper roomMapper = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getBean(WdHtRoomMapper.class);
	    
        
      //获取ShardedJedis对象
        Jedis jedis = jedisPool.getResource();
        
        jedis.flushAll();
        
    	List<WdHtRoom> list = roomMapper.selectAll(null);
    	if(list!=null&&list.size()>0)
    	{
    		JSONArray jsonArray = JSONArray.fromObject(list);
	         //存入键值对
	        jedis.set("rooms", jsonArray.toString());
    	}
         //回收ShardedJedis实例
        jedis.close();
	}

}
